<?php
// +----------------------------------------------------------------------
// | saithink [ saithink快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\process;

use app\cms\model\Project;
use app\model\DownloadZip;
use Workerman\Connection\TcpConnection;
use plugin\saiadmin\utils\JwtAuth;

class WebSocket
{

    public $connectionArray = [];

    public function onConnect(TcpConnection $connection)
    {
        // websocket连接
        $connection->onWebSocketConnect = function ($connection, $http_buffer) {
            // 可以在这里判断连接来源是否合法，不合法就关掉连接
            $domain = $_SERVER['HTTP_ORIGIN'];

            // 通过token进行用户认证
            try {
                $token = $_GET['token'];
                $key = config('plugin.saiadmin.saithink.cross.jwt_key', 'sai_admin');

                $jwt = new JwtAuth($key);
                $user = $jwt->parseToken($token);
            } catch (\Exception $e) {
                // var_dump($e->getMessage());
                $connection->close();
            }
        };

        // 消息处理  前端请求 ws.send(内容)  =  $data
        $connection->onMessage = function ($connection, $data) {
            // 收到客户端消息
            // 客户端传递用户id
            // 查询用户申请的下载zip是否已经完成，完成了把对应的下载链接地址消息推送给用户
            $data = json_decode($data, true);
            // var_dump($data['userId']);
            $userId = isset($data['userId']) ? $data['userId'] : '';
            if (!empty($userId)) {
                $downloadList = DownloadZip::where(['status' => 1, 'created_by' => $userId, 'read_status' => 0])->select()->toArray();
                // var_dump($downloadList);
                $data = [];
                foreach ($downloadList as $key => $val) {
                    $project = Project::find($val['project_id']);
                    var_export($project);
                    if (!empty($project)) {
                        $projectName = isset($project->project_name) ? $project->project_name : '未填写项目名称 - ';
                        $data[$key]['id'] = $val['id'];
                        $data[$key]['title'] =  $projectName . ' 文件下载已完成';
                        $data[$key]['content'] = $projectName . ' 文件压缩包已经打包完成，请点击链接去下载：' . '<a href="' . $project->project_download_zip . '"> 点击下载</a>';
                        $data[$key]['create_time'] = date('Y-m-d H:i:s');
                        $data[$key]['send_user'] = [
                            'nickname' => '系统管理员',
                            'avatar' => ''
                        ];
                    }
                }

                // var_dump($data);
            }

            // 向客户端发送消息
            $return_ret = [
                'event' => 'ev_new_message',
                'message' => '新消息通知',
                'data' => $data
            ];
            $connection->send(json_encode($return_ret));
        };

        // 连接关闭
        $connection->onClose = function ($connection) {
            $connection->close();
        };
    }

    public function onClose(TcpConnection $connection)
    {
        // 关闭websocket
        $connection->close();
    }
}
